<template>
  <div class="zh-batch-import">
    <nav-header>
      <template slot="menuBefore">
        <li><router-link to="/user/user/platform-user" tag="a">平台用户管理</router-link></li>
        <li class="gap">&gt;</li>
      </template>
    </nav-header>
    <div class="zh-import-comter">
      <el-button @click="downloadDemo" class="downLoadtemplate">下载模板</el-button>
      <uploader :options="uploadOptions" :autoStart="false" ref="uploader" :file-status-text="statusText"
        @files-submitted="fileSubmit" @file-removed="fileRemoved" @file-success="fileSuccess" @file-error="fileFail"
        class="uploader-example">
        <uploader-unsupport></uploader-unsupport>
        <uploader-btn :directory="false" :attrs="attrs" class="select_file" v-if="selectFileShow"
          :single="true">导入Excel</uploader-btn>
        <uploader-btn :directory="false" :attrs="attrsFace" style="margin-left: 20px;" class="select_file"
          v-if="selectFileShow" :single="true">导入人脸照片</uploader-btn>

        <uploader-list v-if="!selectFileShow"></uploader-list>
      </uploader>
      <el-button type="primary" v-if="!selectFileShow" @click="fileUpload" style="margin-top: 10px;">确定导入</el-button>
    </div>
    <div class="zh-import-text">
      <p>注意事项: </p>
      <p>1.格式支持：Excel2003版本及以上的<span>xls/xlsx</span>格式</p>
      <p>2.EXcel表数据从第二行开始有效。<span>表中数据均为必填项</span>。</p>
      <p>3.批量导入用户默认密码为<span>Admin@1993</span>，导入后用户可以在账户设置中修改密码</p>
      <p>4.角色信息请在批量导入后进行绑定，如年级班级、科目等 数据</p>
      <p>5.导入人脸照片，只支持压缩包格式zip。请以系统的用户账号作为文件名称，否则将会导入失败。可参照示例2进行命名。</p>
    </div>
    <div class="zh-import-table">
      <p>示例1：</p>
      <div class="zh-table">
        <div class="zh-table-contents">
          <el-table :data="importData" border style="width: 100%">
            <el-table-column prop="1" label="帐号" align="center" show-overflow-tooltip>
            </el-table-column>
            <el-table-column prop="2" label="姓名" align="center" show-overflow-tooltip>
            </el-table-column>
            <el-table-column prop="3" label="角色" align="center" show-overflow-tooltip>
            </el-table-column>
            <el-table-column prop="4" label="性别" align="center" show-overflow-tooltip>
            </el-table-column>
            <el-table-column prop="5" label="学段" align="center" show-overflow-tooltip>
            </el-table-column>
            <el-table-column prop="6" label="年级" align="center" show-overflow-tooltip>
            </el-table-column>
            <el-table-column prop="7" label="班级" align="center" show-overflow-tooltip>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div>
        <p>示例2：</p>
        <div>
          <img style="width: 100px;height: 130px;" src="../../../../static/image/face_img.jpg" />
          <div>lina.jpg</div>
        </div>
      </div>
    </div>


    <!-- 上传文件错误弹窗 -->
    <el-dialog :close-on-click-modal="false" :close-on-press-escape="false" title="上传错误" :visible.sync="showError"
      class="uploadError" width="650px">
      <ul>
        <li v-for="(item, idx) in errorMsg" :key="idx">{{ item }}</li>
      </ul>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="showError = false">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { downloadBatchDemo, uploaderFileFail, longTimeMessage } from './../../../tools/tool';

export default {
  data() {
    return {
      app_code: sessionStorage.getItem('CheckSchoolAppCode'),
      messageObj: {},
      statusText: {
        success: '上传成功',
        error: '上传出错',
        uploading: '正在上传...',
        paused: '暂停',
        waiting: '等待上传'
      },
      selectFileOrNot: false,  //是否选中文件
      uploadOrNot: false, 		//是否已经上传
      uploadInfo: {
        file_name: '',
        file_path: '',
        file_size: 0
      },
      attrs: {
        accept: ['application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet']
      },
      attrsFace: {
        accept: ['application/zip']
      },
      uploadOptions: {
        target: this.BASE_URL + '/api/user/vue_userdemo_upload',
        testChunks: false,
        headers: { Authorization: `Bearer ` + this.$g.access_token },
      },
      fileList: [],
      rules: {
      },
      selectFileShow: true,//是否显示选择文件按钮
      uploadRetryTimes: 100,//文件最大重传次数
      importData: [
        {
          1: "lvxiaoyu",
          2: "吕小鱼",
          3: "学生",
          4: "女",
          5: "小学",
          6: "一年级",
          7: "1班",
        },
        {
          1: "lvshu",
          2: "吕树",
          3: "学生",
          4: "男",
          5: "高中",
          6: "高一",
          7: "1班",
        }
      ],
      excelUploader: null, // 上传组件引用
      showError: false,   // 控制错误弹窗显隐
      errorMsg: [],   // 存放上传错误信息
      uploadApi: 'api/user/vue_user_import'
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.excelUploader = this.$refs.uploader.uploader;
    })
  },
  methods: {
    /**
     * 下载导出模板
     */
    downloadDemo() {
      let url = this.BASE_URL + '/index/resource/user_import_demo' + '&app_code=' + this.app_code;
      downloadBatchDemo(url);
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.selectFileOrNot) {
            this.fileUpload();
          } else {
            this.resourceSave();
          }
        } else {
          return false;
        }
      });
    },
    resourceSave() {
      let resourceParam = {};
      if (this.uploadOrNot) {
        resourceParam.path = this.uploadInfo.file_path;
      }
      let success = (data => {
        this.$message.success(data.msg);

        setTimeout(() => {
          this.$router.push('/user/user/platform-user');
        }, 1000);
      })
      let fail = (res => {
        // longTimeMessage(this, res, 15000);
        this.errorMsg = typeof res.msg == 'string' ? [res.msg] : res.msg;
        this.showError = true;
      })
      // api/user/vue_user_import
      this.$ajax.post(this.uploadApi, resourceParam, { func: { success: success, fail: fail } })
    },
    //上传成功的事件
    fileSuccess(rootFile, file, message, chunk) {
      this.selectFileShow = true;
      var mess = eval('(' + message + ')');
      mess = handleResponseData(mess);
      console.log('---', file)
      // return
      if (parseInt(mess.data.status) === 1) {
        this.uploadOrNot = true;
        this.uploadInfo.file_name = mess.data.file_name;
        this.uploadInfo.file_path = mess.data.file_path;
        this.uploadInfo.post_fix = mess.data.post_fix;
        this.uploadApi = 'api/user/vue_user_import'
        if (file.fileType === 'application/zip') {
          this.uploadApi = 'api/user/userFaceImport'
        }
        this.resourceSave();
      }
      this.excelUploader.removeFile(file);
    },
    fileFail(rootFile, file, message, chunk) {
      uploaderFileFail(this, this.excelUploader, file, message);
    },
    //文件添加到上传队列后触发 -- 过滤文件格式
    fileSubmit(files, fileList, event) {
      for (var i = 0; i < fileList.length; i++) {
        if (this.excelUploader.fileList.length > 1) {
          this.excelUploader.removeFile(this.excelUploader.fileList[0]);
        }

        this.uploadInfo.file_size = fileList[i].size;
        this.selectFileOrNot = true;
        this.selectFileShow = false;
      }
    },
    fileRemoved(file) {
      this.selectFileOrNot = false;
      this.selectFileShow = true;
    },
    fileUpload() {
      // 开始或继续上传
      this.excelUploader.upload();
    },
  },
  destroyed(to, from, next) {
    this.$message.closeAll();
  },
}
</script>
<style lang="scss">
.zh-batch-import {
  .zh-import-comter {
    margin-top: 20px;
  }

  .uploader-example {
    margin-top: 20px;
  }

  .zh-import-text {
    font-size: 12px;
    color: #999;
    line-height: 30px;
    margin: 20px;

    p {
      margin: 0;
    }

    span {
      color: red;
    }
  }

  .zh-import-table {
    p {
      font-size: 16px;
      margin-bottom: 20px;
    }

    .zh-table-contents .el-table__header-wrapper table thead tr {

      th:nth-child(1),
      th:nth-child(2),
      th:nth-child(3),
      th:nth-child(4) {
        color: red;
      }
    }
  }

  .uploader-list {
    .uploader-file-pause {
      display: none !important;
    }

    .uploader-file-status {
      text-indent: 0;
    }
  }

  .uploadError .el-dialog__body {
    ul {
      margin-bottom: 20px;
      max-height: 300px;
      overflow-x: hidden;
      color: #FF3131
    }

  }

  .select_file {
    background-color: #348efc;
    color: #fff;
    border: none;
    width: 84px;
    height: 22px;
    line-height: 22px;
    text-align: center;
  }

  .uploader-btn:hover {
    background-color: #348efc !important
  }

  .downLoadtemplate {
    height: 30px;
    width: 100px;
    margin-right: 20px;
    background-color: #deefff;
  }
}
</style>
